﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DevExpress.XtraEditors;


namespace YJY_DMZS.BasisFile
{
    public partial class FrmUserEditor : XtraForm
    {
        /// <summary>
        /// 主键值，非正零为新增
        /// </summary>
        public int t_userid;
        /// <summary>
        /// 标题栏文字格式
        /// </summary>
        private string captionFormat;
        /// <summary>
        /// 职工
        /// </summary>
        private DMZS.Model.Employee employee;


        #region ================================初始化=====================================
        public FrmUserEditor()
        {
            InitializeComponent();
        }

        private void FrmUserEditor_Load(object sender, EventArgs e)
        {
            captionFormat = Text;
        }

        private void FrmUserEditor_Shown(object sender, EventArgs e)
        {
            if (t_userid <= 0)
            {
                NewRecord();
            }
            else
            {
                LoadData(t_userid);
            }
        }

        //enter -> tab
        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (keyData == Keys.Enter && !(this.ActiveControl.Parent is ButtonEdit))
            {
                keyData = Keys.Tab;
            }

            return base.ProcessDialogKey(keyData);
        }
        #endregion ================================初始化=====================================


        #region ================================功能函数区=====================================

        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="t_userid">用户id</param>
        private void LoadData(int t_userid)
        {
            var bll = new DMZS.BLL.t_user();
            var data = bll.GetRecordByID(t_userid);

            if (data == null)
            {
                XtraMessageBox.Show("该条数据已经被删除，请刷新数据", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                NewRecord();
                return;
            }

            Text = string.Format(captionFormat, "维护");
            txtt_name.Text = data.Rows[0]["t_name"].ToString();
            txtt_pwd.Text = data.Rows[0]["t_pwd"].ToString();
            txtt_lastdate.Text = string.Format("{0:yyyy-MM-dd}", data.Rows[0]["t_lastdate"].ToString());
            txtt_count.Text = data.Rows[0]["t_count"].ToString();
            mmot_remark.Text = data.Rows[0]["t_remark"].ToString();

            if (data.Rows[0]["EtypeFID"] != DBNull.Value && Convert.ToInt32(data.Rows[0]["EtypeFID"]) > 0)
            {
                DMZS.BLL.Employee bll_employee = new DMZS.BLL.Employee();
                employee = bll_employee.GetModel(Convert.ToInt32(data.Rows[0]["EtypeFID"]));
            }
            else
            {
                employee = null;
            }
            bteEmployee.Text = employee == null ? "" : employee.Name;
            chkisSystem.Checked = Convert.ToBoolean(data.Rows[0]["isSystem"]);

            if (chkisSystem.Checked)
            {
                btnDelete.Enabled = false;
            }
            else
            {
                btnDelete.Enabled = true;
            }
            txtt_name.Properties.ReadOnly = true;
            txtt_name.TabStop = false;

            mmot_remark.Focus();
        }

        /// <summary>
        /// 新记录
        /// </summary>
        private void NewRecord()
        {
            Text = string.Format(captionFormat, "新增");
            t_userid = 0;
            txtt_name.Text = string.Empty;
            txtt_pwd.Text = string.Empty;
            txtt_lastdate.Text = "";
            txtt_count.Text = "0";
            mmot_remark.Text = string.Empty;
            employee = null;
            bteEmployee.Text = "";
            chkisSystem.Checked = false;

            btnDelete.Enabled = true;
            txtt_name.Properties.ReadOnly = false;
            txtt_name.TabStop = true;

            txtt_name.Focus();
        }

        /// <summary>
        /// 重置界面数据,刷新
        /// </summary>
        /// <param name="t_userid">非整数位新增</param>
        private void ResetInterface(int t_userid)
        {
            if (t_userid <= 0)
            {
                NewRecord();
            }
            else
            {
                LoadData(t_userid);
            }
        }

        /// <summary>
        /// 保存新记录
        /// </summary>
        private void SavaNew()
        {
            var model = new DMZS.Model.t_user();
            var bll = new DMZS.BLL.t_user();

            model.t_name = txtt_name.Text.Trim();
            model.t_pwd = txtt_pwd.Text.Trim();
            model.t_lastdate = null;
            model.t_count = 0;
            model.t_remark = mmot_remark.Text;
            model.isSystem = Convert.ToInt32(chkisSystem.Checked);
            model.Deleted = false;
            model.EtypeFID = Convert.ToInt32(employee == null ? 0 : employee.ID);

            var result = bll.AddExpand(model);
            if (result == -1001)
            {
                XtraMessageBox.Show("该用户名已被注册。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                txtt_name.SelectAll();
                txtt_name.Focus();
            }
            else
            {
                if (result == -1002)
                {
                    XtraMessageBox.Show("该职员编号不存在。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    bteEmployee.Focus();
                    bteEmployee.SelectAll();
                    employee = null;
                }
                else
                {
                    if (result != 0)
                    {
                        XtraMessageBox.Show("保存成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        t_userid = result;
                        LoadData(t_userid);
                    }
                    else
                    {
                        XtraMessageBox.Show("添加失败，建议重新打开界面。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    }
                }
            }
        }

        /// <summary>
        /// 保存修改
        /// </summary>
        private void SaveModify()
        {
            var model = new DMZS.Model.t_user();
            var bll = new DMZS.BLL.t_user();

            model.t_userid = t_userid;
            model.t_name = txtt_name.Text.Trim();
            model.t_pwd = txtt_pwd.Text.Trim();
            //model.t_lastdate = null;
            model.t_count = 0;
            model.t_remark = mmot_remark.Text;
            model.isSystem = Convert.ToInt32(chkisSystem.Checked);
            model.Deleted = false;
            model.EtypeFID = Convert.ToInt32(employee == null ? 0 : employee.ID);

            var result = bll.UpdateExpand(model);
            if (result == -1001)
            {
                XtraMessageBox.Show("该用户名已被注册。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                txtt_name.SelectAll();
                txtt_name.Focus();
            }
            else
            {
                if (result == -1002)
                {
                    XtraMessageBox.Show("该职员编号不存在。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    bteEmployee.Focus();
                    bteEmployee.SelectAll();
                    employee = null;
                }
                else
                {
                    if (result != 0)
                    {
                        XtraMessageBox.Show("保存成功。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                        t_userid = result;
                        LoadData(t_userid);
                    }
                    else
                    {
                        XtraMessageBox.Show("添加失败，建议重新打开界面。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                    }
                }
            }
        }

        /// <summary>
        /// 验证输入
        /// </summary>
        /// <returns></returns>
        private bool ValidateInput()
        {
            if (txtt_name.Text.Trim().Length == 0)
            {
                XtraMessageBox.Show("请输入用户名。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                txtt_name.Focus();
                return false;
            }
            return true;
        }

        /// <summary>
        /// 验证职工
        /// </summary>
        /// <returns></returns>
        private bool ValidateEmployee()
        {
            if (bteEmployee.Text.Trim().Length == 0)
            {
                employee = null;
                return true;
            }

            var bll = new DMZS.BLL.Employee();
            var model = new DMZS.Model.Employee();

            model = bll.GetModel(bteEmployee.Text.Trim());
            if (model == null)
            {
                XtraMessageBox.Show("该职员编号不存在。", Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                bteEmployee.Focus();
                bteEmployee.SelectAll();
                return false;
            }
            else
            {
                employee = model;
                return true;
            }
        }
        #endregion ================================功能函数区=====================================


        #region ================================工具栏按钮事件=====================================

        //第一条
        private void btnFirst_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var bll = new DMZS.BLL.t_user();
            var row = bll.GetFirst();
            if (row != null)
            {
                t_userid = Convert.ToInt32(row["t_userid"]);
                LoadData(t_userid);
            }
            else
            {
                NewRecord();
            }
        }

        //上一条
        private void btnPrevious_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (t_userid <= 0)
            {
                return;
            }
            var bll = new DMZS.BLL.t_user();
            var row = bll.GetPrevious(t_userid);
            if (row != null)
            {
                t_userid = Convert.ToInt32(row["t_userid"]);
                LoadData(t_userid);
            }
            else
            {
                LoadData(t_userid);
            }
        }

        //下一条
        private void btnNext_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (t_userid <= 0)
            {
                return;
            }
            var bll = new DMZS.BLL.t_user();
            var row = bll.GetNext(t_userid);
            if (row != null)
            {
                t_userid = Convert.ToInt32(row["t_userid"]);
                LoadData(t_userid);
            }
            else
            {
                LoadData(t_userid);
            }
        }

        //最后条
        private void btnLast_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var bll = new DMZS.BLL.t_user();
            var row = bll.GetLast();
            if (row != null)
            {
                t_userid = Convert.ToInt32(row["t_userid"]);
                LoadData(t_userid);
            }
            else
            {
                NewRecord();
            }
        }

        //新记录
        private void btnNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (t_userid <= 0)
            {
                return;
            }
            NewRecord();
        }

        //删除
        private void btnDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (t_userid <= 0)
            {
                NewRecord();
                return;
            }
            else
            {
                if (DialogResult.No == XtraMessageBox.Show("确认删除?", Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1))
                {
                    return;
                }
            }
            var bll = new DMZS.BLL.t_user();
            bll.Delete(t_userid);

            NewRecord();
        }

        //保存
        private void btnSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!ValidateInput())
            {
                return;
            }
            if (t_userid <= 0)
            {
                SavaNew();
            }
            else
            {
                SaveModify();
            }
        }

        //刷新
        private void btnRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ResetInterface(t_userid);
        }

        #endregion ================================工具栏按钮事件=====================================


        #region ================================职工输入框事件=====================================
        //职工输入框 焦点进入
        private void bteEmployee_Enter(object sender, EventArgs e)
        {
            bteEmployee.Text = employee == null ? "" : employee.Code;
        }

        //职工输入框 回车
        private void bteEmployee_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                if (ValidateEmployee()) SendKeys.Send("{TAB}");
            }
        }

        //职工输入框 焦点离开
        private void bteEmployee_Leave(object sender, EventArgs e)
        {
            bteEmployee.Text = employee == null ? "" : employee.Name;

        }

        //职工输入框 按钮
        private void bteEmployee_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            DialogForm.FrmEmployee_dlg frm = new DialogForm.FrmEmployee_dlg();
            frm.MultiSelect = false;
            frm.ReturnList += new DialogForm.FrmEmployee_dlg.ReturnListEventHandler(frm_ReturnList);
            frm.ShowDialog();
        }

        void frm_ReturnList(List<System.Data.DataRow> lists)
        {
            if (lists.Count == 0) return;

            var bll = new DMZS.BLL.Employee();
            var model = bll.GetModel(Convert.ToInt64(lists[0]["ID"]));
            if (model != null)
            {
                employee = model;
                bteEmployee.Text = model.Code;
            }
        }
        #endregion ================================职工输入框事件=====================================




    }
}
